<?php
declare (strict_types=1);

namespace addons\substation\library;
use think\template\TagLib;

class HkCms extends TagLib
{
    /**
     * 定义标签列表
     */
    protected $tags   =  [
        'substation' => ['attr'=>'where,id,parent_id,new_window,lang', 'close'=>1],  // 调取分站
    ];

	/**
     * 获取分站链接
     * @param $tag
     * @param $content
     * @return string
     */
    public function tagSubstation($tag, $content)
    {
        $tag['id'] = !empty($tag['id']) ? $tag['id'] : 'item';
		$tag['parent_id'] = !empty($tag['parent_id']) ? $tag['parent_id'] : '';
		$tag['new_window'] = !empty($tag['new_window']) ? $tag['new_window'] : '';
        $tag['where'] = !empty($tag['where']) ? $this->parseCondition($tag['where']) : '';
        $parseStr = '<?php'."\r\n";
        $parseStr .= '$__LIST__ = (new \app\admin\model\Substation)->getList('.self::arrToHtml($tag).');'."\r\n";
        $parseStr .= '?>';
        $parseStr .= '{volist name="__LIST__" id="'.$tag['id'].'"}';
        $parseStr .= $content;
        $parseStr .= '{/volist}';
        return $parseStr;
    }
	
	/**
     * 转换数据为HTML代码
     * @param $data
     * @return string
     */
    private static function arrToHtml($data)
    {
        if (is_array($data)) {
            $str = '[';
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    $str .= "'$key'=>" . self::arrToHtml($val) . ",";
                } else {
                    //如果是变量的情况
                    if (is_int($val)) {
                        $str .= "'$key'=>$val,";
                    } else if (strpos($val, '$') === 0) {
                        $str .= "'$key'=>$val,";
                    } else if (preg_match("/^([a-zA-Z_].*)\(/i", $val, $matches)) {//判断是否使用函数
                        if (function_exists($matches[1])) {
                            $str .= "'$key'=>$val,";
                        } else {
                            $str .= "'$key'=>'" . self::newAddslashes($val) . "',";
                        }
                    } else {
                        $str .= "'$key'=>'" . self::newAddslashes($val) . "',";
                    }
                }
            }
            $str = rtrim($str,',');
            return $str . ']';
        }
        return '';
    }

    /**
     * 返回经addslashes处理过的字符串或数组
     * @param string $string 需要处理的字符串或数组
     * @return mixed
     */
    private static function newAddslashes($string)
    {
        if (!is_array($string)) {
            return addslashes($string);
        }
        foreach ($string as $key => $val) {
            $string[$key] = self::newAddslashes($val);
        }
        return $string;
    }
}